package com.qf.zyh.dao.Impl;

import com.qf.zyh.dao.UserDao;
import com.qf.zyh.entity.User;
import com.qf.zyh.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

public class UserDaoImpl implements UserDao {
    private QueryRunner qr=new QueryRunner();
    @Override
    public List<User> selectAll() {
        try {
            return qr.query(DBUtil.getConnection(),"select uid,uname,upassword,uemail,usex,ustatus,ucode,urole from user",new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User selectName(String name) {
        try {
            return qr.query(DBUtil.getConnection(),"select uid,uname,upassword,uemail,usex,ustatus,ucode,urole from user where uname=?",new BeanHandler<>(User.class),name);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int addUser(User user) {
        try {
            int update = qr.update(DBUtil.getConnection(), "insert into user values(default,?,?,?,?,?,?,?)", user.getUname(), user.getUpassword(), user.getUemail(), user.getUsex(), user.getUstatus(), user.getUcode(), user.getUrole());
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public User getUserByEmailAndCode(String c, String e) {
        try {
            return qr.query(DBUtil.getConnection(),"select uid,uname,upassword,uemail,usex,ustatus,ucode,urole from user where uemail=? and ucode=?",new BeanHandler<>(User.class),e,c);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    public int updateUserStatus(int activate, int uid) {
        try {
            int update = qr.update(DBUtil.getConnection(), "update user set ustatus=? where uid=?",activate, uid);
            return update;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
